import React, { useMemo, useState, useCallback } from 'react';
import { 
  Space, 
  Typography, 
  Button, 
  Tag, 
  Badge
} from 'antd';
import { VariableSizeList as VirtualList } from 'react-window';

const { Text } = Typography;

interface Problem {
  id: string;
  lineNumber: number;
  columnNumber: number;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  category: string;
  description: string;
  suggestion: string;
  ruleName?: string;
  originalCode?: string;
  suggestedCode?: string;
  sqlFragment?: string; // 新增SQL片段字段
}

interface ProblemGroup {
  key: string;
  title: string;
  icon: React.ReactNode;
  count: number;
  items: Problem[];
  color: string;
}

interface VirtualizedProblemListProps {
  problems: ProblemGroup[];
  selectedIssueId?: string | null;
  onIssueClick?: (issue: Problem) => void;
  height?: number;
}

const VirtualizedProblemList: React.FC<VirtualizedProblemListProps> = ({
  problems,
  selectedIssueId,
  onIssueClick,
  height = 400
}) => {
  const [expandedGroups, setExpandedGroups] = useState<string[]>(['HIGH', 'MEDIUM']);

  // 过滤后的问题列表
  const filteredProblems = useMemo(() => {
    return problems.map(group => {
      // 去除重复项（基于id去重）
      const uniqueItems = group.items.filter((item, index, arr) => 
        arr.findIndex(i => i.id === item.id) === index
      );

      return {
        ...group,
        items: uniqueItems,
        count: uniqueItems.length
      };
    }).filter(group => group.count > 0);
  }, [problems]);

  // 展开的问题列表（用于虚拟滚动）
  const flatProblems = useMemo(() => {
    const result: Array<{ 
      type: 'group' | 'item'; 
      data: any; 
      groupKey?: string; 
      uniqueId: string 
    }> = [];
    
    filteredProblems.forEach(group => {
      // 添加分组标题
      result.push({ 
        type: 'group', 
        data: group, 
        uniqueId: `group-${group.key}` 
      });
      
      // 如果分组展开，添加问题项
      if (expandedGroups.includes(group.key)) {
        group.items.forEach((item, itemIndex) => {
          result.push({ 
            type: 'item', 
            data: item, 
            groupKey: group.key,
            uniqueId: `item-${group.key}-${item.id}-${itemIndex}`
          });
        });
      }
    });
    
    return result;
  }, [filteredProblems, expandedGroups]);

  // 处理分组展开/折叠
  const handleGroupToggle = useCallback((groupKey: string) => {
    setExpandedGroups(prev => 
      prev.includes(groupKey) 
        ? prev.filter(key => key !== groupKey)
        : [...prev, groupKey]
    );
  }, []);



  // 计算每个列表项的高度
  const getItemSize = useCallback((index: number) => {
    const item = flatProblems[index];
    
    if (item.type === 'group') {
      return 60; // 分组头部固定高度
    } else {
      const problem = item.data as Problem;
      let baseHeight = 100; // 简化后的基础高度：padding(16) + header(32) + description(40) + margins(12)
      
      // 根据描述长度调整高度（估算换行）
      const descriptionLines = Math.ceil(problem.description.length / 60); // 估算每行60字符
      if (descriptionLines > 2) {
        baseHeight += (descriptionLines - 2) * 20; // 每额外行增加20px
      }
      
      // 如果有代码块，增加高度
      if (problem.originalCode) {
        const codeLines = problem.originalCode.split('\n').length;
        const codeHeight = Math.min(codeLines * 18 + 32, 180); // 限制最大高度
        baseHeight += codeHeight;
      }
      
      // 如果有建议，增加高度
      if (problem.suggestion) {
        const suggestionLines = Math.ceil(problem.suggestion.length / 60);
        baseHeight += Math.max(suggestionLines * 16 + 20, 36); // 最小36px
      }
      
      return Math.max(baseHeight, 80); // 保证最小高度
    }
  }, [flatProblems]);

  // 获取严重程度标签
  const getSeverityTag = (severity: string) => {
    const colors = {
      'HIGH': 'error',
      'MEDIUM': 'warning',
      'LOW': 'processing',
      'INFO': 'success'
    };
    return (
      <Tag color={colors[severity as keyof typeof colors] || 'default'}>
        {severity}
      </Tag>
    );
  };

  // 渲染虚拟列表项
  const renderListItem = ({ index, style }: { index: number; style: React.CSSProperties }) => {
    const item = flatProblems[index];
    
    if (item.type === 'group') {
      const group = item.data as ProblemGroup;
      const isExpanded = expandedGroups.includes(group.key);
      
      return (
        <div key={item.uniqueId} style={style}>
          <div 
            className={`problem-group-header ${isExpanded ? 'expanded' : ''}`}
            onClick={() => handleGroupToggle(group.key)}
          >
            <Space>
              {group.icon}
              <span className="group-title">{group.title}</span>
              <Badge count={group.count} style={{ backgroundColor: group.color }} />
            </Space>
            <Button type="text" size="small">
              {isExpanded ? '收起' : '展开'}
            </Button>
          </div>
        </div>
      );
    } else {
      const problem = item.data as Problem;
      const isActive = selectedIssueId === problem.id;
      
      return (
        <div key={item.uniqueId} style={style}>
          <div 
            className={`problem-item ${isActive ? 'active' : ''}`}
            onClick={() => onIssueClick && onIssueClick(problem)}
          >
            <div className="problem-item-header">
              <div className="problem-meta">
                {getSeverityTag(problem.severity)}
                <span className="problem-location">第 {problem.lineNumber} 行</span>
                <Tag className="problem-category" color="blue">{problem.category}</Tag>
              </div>
            </div>
            
            <div className="problem-item-content">
              <div className="problem-description">
                {problem.description}
              </div>
              
              {problem.originalCode && (
                <div className="problem-code-section">
                  <div className="code-label">问题代码：</div>
                  <div className="problem-code">
                    <code>{problem.originalCode}</code>
                  </div>
                </div>
              )}
              
              {problem.suggestion && (
                <div className="problem-suggestion">
                  <span className="suggestion-icon">💡</span>
                  <span className="suggestion-text">{problem.suggestion}</span>
                </div>
              )}
            </div>
          </div>
        </div>
      );
    }
  };

  const totalCount = filteredProblems.reduce((sum, group) => sum + group.count, 0);

  return (
    <div className="virtualized-problem-list">
      {/* 简化的操作栏 */}
      <div className="problem-list-header">
        <span className="problem-count">共 {totalCount} 个问题</span>
        <Space size="small">
          <Button 
            type="link" 
            size="small"
            onClick={() => setExpandedGroups(['HIGH', 'MEDIUM', 'LOW', 'INFO'])}
          >
            全部展开
          </Button>
          <Button 
            type="link" 
            size="small"
            onClick={() => setExpandedGroups([])}
          >
            全部收起
          </Button>
        </Space>
      </div>

      {/* 虚拟列表 */}
      <div className="virtual-list-container">
        {flatProblems.length > 0 ? (
          <VirtualList
            height={height}
            itemCount={flatProblems.length}
            itemSize={getItemSize}
            width="100%"
            overscanCount={5}
            style={{ outline: 'none' }}
          >
            {renderListItem}
          </VirtualList>
        ) : (
          <div className="empty-result">
            <Text type="secondary">没有找到匹配的问题</Text>
          </div>
        )}
      </div>
    </div>
  );
};

export default VirtualizedProblemList;